package com.yang.code_sample.id_generate.version1;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;


/**
 * @Description: Id生成器代码版本1, 没有任何重构和改善之前的代码.
 * @Author: 杨 强
 * @CreateTime: 2022-10-17 10:29
 */
public class IdGenerateVersion1 {
    private static final Logger logger = LoggerFactory.getLogger(IdGenerateVersion1.class);

    public static void main(String[] args) {
        System.out.println(generate());
    }

    public static String generate() {
        String id = "";
        try {
            String hostName = InetAddress.getLocalHost().getHostName();
            String[] tokens = hostName.split("\\.");
            if (tokens.length > 0){
                hostName = tokens[tokens.length - 1];
                hostName = hostName.replaceAll("-", "");
            }
            char[] randomChars = new char[8];
            int count = 0;
            Random random = new Random();
            while (count < 8){
                int randomAscii = random.nextInt(122);
                if (randomAscii >= 48 && randomAscii <= 57) {
                    randomChars[count] = (char)('0' + (randomAscii - 48)); count++;
                } else if (randomAscii >= 65 && randomAscii <= 90) {
                    randomChars[count] = (char)('A' + (randomAscii - 65)); count++;
                } else if (randomAscii >= 97 && randomAscii <= 122) {
                    randomChars[count] = (char)('a' + (randomAscii - 97)); count++;
                }
            }
            id = String.format("%s-%d-%s", hostName, System.currentTimeMillis(), new String(randomChars));
        } catch (UnknownHostException e) {
            logger.warn("Failed to get the host name.", e);
        }
        return id;
    }
}
